<template>
  <view>
    <view class="wrap">
      <view class="u-tabs-box">
        <u-tabs-swiper
          ref="tabs"
          :list="list"
          :current="current"
          @change="change"
          :is-scroll="false"
          swiperWidth="750"
          active-color="#202E3C"
          inactive-color="#202E3C"
          font-size="30"
          bar-height="6"
          bar-width="40"
          :bar-style="bac"
          gutter="40"
          :offset="[2, -5]"
        ></u-tabs-swiper>
      </view>
      <u-modal
        v-model="showModel"
        @confirm="confirm"
        title="温馨提示"
        ref="uModal"
        :async-close="true"
        :content="showModelContent"
        :show-cancel-button="true"
      ></u-modal>
      <swiper
        class="swiper-box"
        :current="swiperCurrent"
        @transition="transition"
        @animationfinish="animationfinish"
      >
        <!--       全部 -->
        <swiper-item class="swiper-item" v-for="(f, i) in list" :key="i">
          <scroll-view
            scroll-y
            style="height: 100%; width: 100%"
            :lower-threshold="10"
            class="scroll_wrapper"
          >
            <!--          加载显示  -->
			 <!-- v-if="show" -->
            <view
              style="display: flex; justify-content: center; padding: 30rpx"
              v-if="show"
            >
              <u-loading mode="flower" :show="show"></u-loading>
            </view>
            <!--          无订单显示  -->
            <view
              style="display: flex; justify-content: center; padding: 30rpx"
              class="none_shopping"
              v-if="orderList.length === 0 && !show"
            >
              <image src="/static/None/None_shopping.png"></image>
              <text>暂无订单喔~</text>
            </view>
            <view
              class="order_wrapper"
              v-if="orderList && orderList.length && !show"
              v-for="(item, index) in orderList"
              :key="index"
              @tap.stop="orderToggle(item)"
            >
              <view class="title_wrapper">
                <view class="left_">
                  <image src="/static/order/2.png"></image>
                  <text>
                    订单号：{{item.orderNo}}</text>
                </view>
                <view class="right_" v-if="item.orderStats">{{
                  item.orderStats == "0"
                    ? "待付款"
                    : item.orderStats == "1"
                    ? "待发货"
                    : item.orderStats == "2"
                    ? "待收货"
                    : item.orderStats == "3"
                    ? "已完成"
                
                    : item.orderStats == "-1"
                    ? "取消支付"
                    : ""
                }}</view>
                <!-- <view
                  class="right_"
                  v-if="item.itemType && item.itemType >= 0"
                  >{{
                    item.itemType === 0
                      ? "待审核"
                      : item.itemType === 1
                      ? "待寄回"
                      : item.itemType === 2
                      ? "售后中"
                      : item.itemType === 3
                      ? "售后已完成"
                      : item.itemType === 4
                      ? item.refundName + "已拒绝"
                      : ""
                  }}</view
                > -->
              </view>
              <view class="order_info_wrapper" v-for="(itemgood,indexgood) in item.items" :key="">
                <image :src="httpUrlFn(itemgood.goodsImage)"></image>
                <view class="right_wrapper">
                  <view class="item_1">
                    <view>{{ itemgood.goodsName }}</view>
                    <view>￥{{ itemgood.goodsPrice }}</view>
                  </view>
                  <!--                  <view class="item_2">-->
                  <!--                    <view>佣金:￥{{ item.commission }}</view>-->
                  <!--                  </view>-->
                  <view class="item_3">
                    <view>规格：{{itemgood.goodsSpec}}</view>
                    <view>×{{ itemgood.goodsNumber}}</view>
                  </view>
                </view>
              </view>
              <view class="money_wrapper">
                <view>
                  <view>共{{ item.orderNum }}件</view>
                  <view
                    >商品小计：<text>￥{{ item.allPrice }}</text></view
                  >
                </view>
              </view>
              <view class="but_wrapper">
                <view
                  class="left_wrapper"
                  v-if="item.itemType && item.itemType >= 0"
                >
                  售后状态：
                  {{
                    item.itemType === 0
                      ? "待审核"
                      : item.itemType === 1
                      ? "待寄回"
                      : item.itemType === 2
                      ? "售后中"
                      : item.itemType === 3
                      ? "售后已完成"
                      : item.itemType === 4
                      ? item.refundName + "已拒绝"
                      : ""
                  }}
                </view>
                <view class="right_wrapper">
                  <!--                待付款  -->
				  <!--  -->
                  <view
                    class="cancellation_"
                    v-if="item.orderStats == '0'"
                    @tap.stop="cancellationFn(item, index, 4)"
                    >取消订单</view
                  >
                  <!--               待付款   -->
                  <view
                    class="payment_"
                    v-if="item.orderStats == '0'"
                    @tap.stop="paymentFn(item, index)"
                    >立即支付</view
                  >
                  <!--                待发货  -->
                  <!-- <view
                    class="refund_"
                    v-if="item.orderStats == '1' || item.status == '3'"
                    @tap.s.stop="cancellationFn(item, index, 5)"
                    >申请售后</view
                  > -->
                  <!--                待收货和已收货  -->
                  <!-- <view
                    class="logistics_"
                    v-if="item.status == '2' || item.status == '3'"
                    @tap.stop="logisticsFn(item, index)"
                    >查看物流</view
                  > -->
                  <!--                待收货  -->
                  <view
                    class="confirm_"
                    v-if="item.orderStats == '2'"
                    @tap.stop="cancellationFn(item, index, 3)"
                    >确认收货</view
                  >
                  <!--                 已收货 -->
                  <!--                  <view class="after_sales_" v-if="item.status === '3'"-->
                  <!--                    >申请售后</view-->
                  <!--                  >-->
                  <!--                 已取消 -->
                  <view
                    class="delete_order_"
                    v-if="item.orderStats == '-1'"
                    @tap.stop="cancellationFn(item, index, '-1')"
                    >删除订单</view
                  >
                  <!-- <view
                    class="cancelRefund"
                    v-if="item.status == '5' && item.itemType == 0"
                    @tap.stop="cancellationFn(item, index, '-3')"
                    >取消售后</view
                  >
                  <view
                    class="refund_ refund_wrapper"
                    v-if="
                      (item.status == '5' && item.itemType === 3) ||
                      item.itemType === 4
                    "
                    @tap.s.stop="cancellationFn(item, index, 5)"
                    >重新申请</view
                  > -->
                </view>
              </view>
            </view>
            <u-loadmore
              v-if="orderList.length > 0 && !show"
              :status="status"
              :icon-type="iconType"
              :load-text="loadText"
              @loadmore="loadNextFn"
              class="loadmore_wrapper"
            />
          </scroll-view>
        </swiper-item>
      </swiper>
    </view>
  </view>
</template>

<script>
import {
  getGoodsOrderPage,
  cancelGoodsOrder,
  delGoodsOrder,
  confirmGoodsOrderArrival,
  payOrderCallbackTest,
  
  
  cancelApi,
  cancelDelete,
  getOrderTokenByOrderSn,
  orderInfoByTypeAndStatus,
  updateOrderStatusByOrderSn,
  weixinPay,
} from "@/api/orderApi";
import { BASE_URL_IMAHE } from "../../../../utils/https";
import { randomDerate } from "@/api/address";

export default {
  watch: {
    swiperCurrent(newValue, oldValue) {
      this.order.pageSize = 10;
      this.order.pageNo = 1;
      this.orderFilter = [];
      this.myOrder();
      console.log(newValue, "新的");
      console.log(oldValue, "旧的");
    },
  },
  data() {
    return {
      //订单更新状态用
      orderUpdata: {},
      //原数组
      orderList: {
        // records: [],
      },
      //用于条件渲染的数组
      orderFilter: [],
      bac: {
        background: "red",
      },
      status: "loadmore",
      iconType: "flower",
      loadText: {
        loadmore: "点击加载更多",
        loading: "正在加载，请喝杯茶...",
        nomore: "哼~😕我也是有底线的~",
        //哼~😕我也是有底线的~
        //😕我也是有底线的~
      },
      page: 0,
      pageSize: 10,
      show: false,
      list: [
        {
          name: "全部",
        },
        {
          name: "待付款",
        },
        {
          name: "待发货",
        },
        {
          name: "待收货",
        },
        {
          name: "已完成",
          count: 0,
        },
        {
          name: "已取消",
        },
      ],
      orderType: [],
      // 因为内部的滑动机制限制，请将tabs组件和swiper组件的current用不同变量赋值
      current: 0, //tabs组件的current值，表示当前活动的tab选项
      swiperCurrent: 0, // swiper组件的current值，表示当前那个swiper-item是活动的
      tabsHeight: 0,
      dx: 0,
      showModel: false,
      showModelContent: "确定要取消订单吗？",
      options: null,
      order: {
		 userId:"",
		  v:"",
		payStats:"",
        // orderType: "", //1->普通订单；2->礼包订单；3->兑换订单;
        orderStats: "", //状态0、待付款 1、待发货 2、待收货 3、已完成 4、已关闭
        pageNo: 1,
        //条数
        pageSize: 10,
      },
	  countnum:0,
    };
  },
  onLoad(options) {
	  // if(options.payUrl){
	  // 	console.log(options.payUrl)
	  // 	return
	  //   window.location.href = options.payUrl; 
	  // }
	this.order.userId=uni.getStorageSync("userId")
	this.order.v=uni.getStorageSync("v")
	
    console.log(options, "传递过来的");
    // 获取传递的对象参数，使用decodeURIComponent解码，并转为对象
    if ("status" in options) {
      this.options = JSON.parse(decodeURIComponent(options.status));
      console.log(this.options, "options");
      // console.log(this.swiperCurrent, "嘻嘻嘻");
    }
	
  },
  onShow() {
    console.log("返回的22");
    this.show = true;
    this.current = +this.options || 0;
    this.order.pageNo = 1;
	this.orderList=[]
    console.log(this.options, "this.options");
    if (this.options === 0) {
      this.swiperCurrent = +this.options || 0;
      this.myOrder();
    } else {
      this.swiperCurrent = +this.options || 0;
    }
  },
  //上拉
  onReachBottom() {
    console.log("触发上拉加载");
    //请求订单
	
	if(this.form.pageNo>this.countnum){
		this.status = "nomore";
		// this.status = "loadmore";
		return
	}
	 
    this.myOrder();
  },
  methods: {
    //b页面返回到a页面的参数
    otherFun(object) {
      console.log(object, "object123");
      if (object) {
        console.log(object);
        this.current = object.current;
        if (object.swiperCurrent === 0) {
          this.swiperCurrent = object.swiperCurrent;
          this.myOrder();
        } else {
          this.swiperCurrent = object.swiperCurrent;
        }
      }
    },

    //点击订单详情
    orderToggle(item) {
      console.log(item, "订单");
      uni.navigateTo({
        url: `/pages/subpackage/orderDetails/index?order=${encodeURIComponent(
          JSON.stringify(item)
        )}&status=1`,
      });
    },

    httpUrlFn(item) {
      if (item) {
        return BASE_URL_IMAHE + item;
      }
      
    },

    //立即支付
    async paymentFn(item, index) {
		if(item.payType==1&&item.payCompany=="XH"){
			window.location.href = item.xhPayUrl; 
		}
	// 	const res = await payOrderCallbackTest (JSON.stringify({outTradeNo:item.id}));
	
 //        if (res.result == 0) {
 //          uni.showToast({
 //            title: "支付成功",
 //            icon: "success",
 //            duration: 2000,
 //          });
	// 	  await this.myOrder();
 //        } else {
 //          uni.showToast({
 //            title: "支付订单错误",
 //            icon: "success",
 //            duration: 2000,
 //          });
 //          return;
        
        //end
      // }
     
      // }
    },

    //请求订单
    async myOrder() {
      this.status = "loading";
       //获取订单的状态
      	  if(this.swiperCurrent > 0){
      		  if(this.swiperCurrent > 4){
      			  this.order.orderStats=-1
      		  }else{
      			  if(this.swiperCurrent==1){
      				  this.order.payStats=0
      				  // this.order.orderStats=0
      				  delete this.order.orderStats
      			  }else{
      				   delete this.order.payStats
      				  this.order.orderStats=  this.swiperCurrent - 1
      			  }
      			  
      		  }
      		
      	  }else{
      		  delete this.order.payStats
      		  this.order.orderStats=""
      	  }
		
	 
      // this.order.orderStats = this.swiperCurrent > 0 ? this.swiperCurrent - 1 : "";
      const res = await getGoodsOrderPage(JSON.stringify(this.order));
      if (res.result == 0) {
        this.show = false;
        //保存原数组
        this.orderList = res.page.list;
		console.log(this.orderList)
		
        this.countnum=Math.ceil(res.page.count/res.page.pageSize)
      
          this.order.pageNo++;
		  
		 console.log(res.page.list.length>=res.page.pageSize)
          setTimeout(() => {
			  if(res.page.list.length>=res.page.pageSize){
				   this.status = "loadmore";
			  }else{
				    this.status = "nomore";
			  }
           
          }, 800);
          // return;
        // }

      } else {
        this.show = false;
      }
    },

    //点击组件触发上拉加载
    loadNextFn() {
      console.log("点击组件触发上拉加载2123");
      //请求订单
      this.myOrder();
    },
    // tab栏切换
    change(index) {
      console.log(index, "tab切换");
      this.swiperCurrent = index;
      //切换状态重新请求
      // this.myOrder()
    },
    // swiper-item左右移动，通知tabs的滑块跟随移动
    transition({ detail: { dx } }) {
      this.$refs.tabs.setDx(dx);
    },
    // 由于swiper的内部机制问题，快速切换swiper不会触发dx的连续变化，需要在结束时重置状态
    // swiper滑动结束，分别设置tabs和swiper的状态
    animationfinish({ detail: { current } }) {
      console.log(current, "位置索引");
      this.$refs.tabs.setFinishCurrent(current);
      this.current = current;
      this.swiperCurrent = current;
      //切换状态重新请求
      // this.myOrder()
    },

    // scroll-view到底部加载更多
    onreachBottom() {
      console.log("到底部 加载更多");
      //请求订单
      this.myOrder();
    },

    //查看物流
    logisticsFn(item, index) {
      console.log(item, index, "物流");
      uni.navigateTo({
        url: `/pages/subpackage/logistics/index?orderSn=${item.orderSn}`,
      });
    },

    //取消订单
    cancellationFn(item, index, num) {
      console.log(this.swiperCurrent, "this.swiperCurrent liang");
      if (num === "-2") return;
      if (num === "-1") {
        this.showModelContent = "是否确认删除订单？";
        this.showModel = true;
        this.orderUpdata = { ...item, index, num };
        return;
      }
      if (num === "-3") {
        this.showModelContent = "是否确认取消售后？";
        this.showModel = true;
        this.orderUpdata = { ...item, index, num };
        return;
      }

      if (num === 4) {
        this.showModelContent = "确定要取消订单吗？";
      } else if (num === 5) {
        this.showModelContent = "是否确定申请退款？";
        const order = { ...item, index, num };
        uni.navigateTo({
          url: `/pages/subpackage/apply_afterSale/index?order=${encodeURIComponent(
            JSON.stringify(order)
          )}`,
        });
      } else if (num === 3) {
        this.showModelContent = "是否确定收货？";
      }
      if (num !== 5) {
        this.showModel = true;
      }
      this.orderUpdata = { ...item, index, num };
      console.log(this.orderUpdata, "orderUpdata 状态");
      console.log(this.orderFilter, "更新");
    },
    //弹窗确认按钮
    async confirm() {
      this.showModel = false;
	  console
      const { id,num,index } = this.orderUpdata;
	  console.log(id,num,"訂單")

      // if (num === "-3") {
      //   const data = {
      //     orderSn: orderSn,
      //   };
      //   const res = await cancelApi(data);
      //   console.log(res, "取消退款");
      //   if (res.code === 0) {
      //     uni.showToast({
      //       title: `取消成功`,
      //       icon: "success",
      //       duration: 2000,
      //     });

      //     this.order.pageNo = 1;
      //     this.orderFilter = [];
      //     this.current = 2;
      //     this.swiperCurrent = 2;
      //     // await this.myOrder();
      //   }
      //   return;
      // }

      if (num == "-1") {
		  
        //删除订单
        const res = await delGoodsOrder({orderId:id});
        console.log(res, "删除订单");
        if (res.result == 0) {
          //根据index删除数组中取消的那一项
          this.orderList.splice(index, 1);
          uni.showToast({
            title: `删除成功`,
            icon: "success",
            duration: 2000,
          });
        }
        return;
      }
	  if(num == "4"){
		  //删除订单
		   // this.orderFilter.splice(index, 1);
		  
		   
		   
		  const res = await cancelGoodsOrder({orderId:id});
		  if (res.result == 0) {
		    //根据index删除数组中取消的那一项
		   await this.myOrder();
		    uni.showToast({
		      title: `订单取消成功`,
		      icon: "success",
		      duration: 2000,
		    });
		  }
		  return;
		  
	  }
	  
	  if(num == "3"){
	  		  //删除订单
	  		   // this.orderFilter.splice(index, 1);
	  		  
	  		   
	  		   
	  		  const res = await confirmGoodsOrderArrival({orderId:id});
	  		  if (res.result == 0) {
	  		    //根据index删除数组中取消的那一项
	  		   await this.myOrder();
	  		    uni.showToast({
	  		      title: `已确认收货`,
	  		      icon: "success",
	  		      duration: 2000,
	  		    });
	  		  }
	  		  return;
	  		  
	  }
	  

      // //确认收货状态：0->未确认；1->已确认
      // const confirmToggle = confirmStatus && confirmStatus > 0 ? 1 : 0;
      // //确认收货时间
      // const time = new Date().getTime();
      // console.log(time, "time");
      // const data = {
      //   orderSn,
      //   status: num,
      //   confirmStatus: confirmStatus && confirmStatus > 0 ? 1 : 0,
      //   receiveTime: confirmToggle === 1 ? time : "",
      // };
      // const prompt = {
      //   5: "申请已提交",
      //   4: "取消订单成功",
      //   3: "确认收货成功",
      // };
      // let res = {};

      // res = await updateOrderStatusByOrderSn(data);
      // if (res.code === 0) {
      //   //根据index删除数组中取消的那一项
      //   console.log(index, "取消订单");
      //   this.orderFilter.splice(index, 1);
      //   if (num !== 4) {
      //     this.order.pageNo = 1;
      //     this.orderFilter = [];
      //     this.current = num + 1;
      //     this.swiperCurrent = num + 1;
      //     // await this.myOrder();
      //   }
      //   uni.showToast({
      //     title: `${prompt[num]}`,
      //     icon: "success",
      //     duration: 2000,
      //   });
      // }
    },
  },
};
</script>

<style>
/* #ifndef H5 */
page {
  height: 100vh;
  background-color: #f2f2f2;
}
/* #endif */
</style>

<style lang="scss" scoped>
page {
  min-height: 100vh;
  background-color: #f2f2f2;
  overflow: auto;
}

.wrap {
  display: flex;
  flex-direction: column;
  height: 100vh;
  overflow: auto;
  width: 100%;
}

.swiper-box::v-deep {
  height: 100%;
  .swiper-item {
    //height: 1000px;
    //padding-top: rpx(12);
    height: 100vh;
    padding-bottom: rpx(16);
    .scroll_wrapper {
      height: 100% !important;
      background: #f5f5f5;
      //padding: rpx(12) rpx(12) rpx(0) rpx(12);
      view.order_wrapper {
        margin: rpx(8) auto rpx(8) auto;
        //margin-bottom: rpx(8);
        width: rpx(351);
        height:auto;
        background: #ffffff;
        border-radius: rpx(5);
        padding: rpx(12);
        .title_wrapper {
          display: flex;
          justify-content: space-between;
          margin-bottom: rpx(8);
          .left_ {
            display: flex;
            align-items: center;
            > image {
              width: rpx(14);
              height: rpx(14);
              margin-right: rpx(4);
              vertical-align: middle;
            }
            .text {
              font-size: rpx(13);
              font-weight: 400;
              color: #353535;
            }
          }
          .right_ {
            font-size: rpx(13);
            font-weight: bold;
            color: #fa5151;
          }
        }
        > .order_info_wrapper {
          display: flex;
		  margin-top: rpx(10);
          > image {
            width: rpx(72);
            height: rpx(72);
          }
          > .right_wrapper {
            flex: 1;
            margin-left: rpx(6);
            display: flex;
            flex-direction: column;
            justify-content: space-between;
            > view {
              display: flex;
            }
            > .item_1 {
              justify-content: space-between;
              margin-bottom: rpx(3);
              view:first-child {
                //width: rpx(168);
                font-size: rpx(12);
                font-weight: 400;
                color: #353535;
                overflow: hidden;
                display: -webkit-box;
                -webkit-box-orient: vertical;
                -webkit-line-clamp: 2; /*最大行数*/
              }
              view:last-child {
                margin-left: rpx(5);
              }
            }
            > .item_2 {
              display: flex;
              margin-bottom: rpx(4);
              > view {
                //height: rpx(16);
                background: rgba(250, 81, 81, 0.1);
                border-radius: rpx(2);
                border: rpx(1) solid #fa5151;
                font-size: rpx(10);
                padding: rpx(1) rpx(3);
                font-weight: 400;
                color: #fa5151;
              }
            }
            > .item_3 {
              font-size: rpx(12);
              font-weight: 400;
              color: #888888;
              display: flex;
              align-items: center;
              justify-content: space-between;
            }
          }
        }
        > .money_wrapper {
          display: flex;
          margin-top: rpx(8);
          > view {
            margin-left: auto;
            display: flex;
            color: #353535;
            font-size: rpx(12);
            view:first-child {
              margin-right: rpx(10);
            }
            view:last-child {
              > text {
                color: #fa5151;
              }
            }
          }
        }
        > .but_wrapper {
          display: flex;
          margin-top: rpx(12);
          .left_wrapper {
            display: flex;
            align-items: center;
          }
          > view.right_wrapper {
            display: flex;
            margin-left: auto;
            //background: red;
            view {
              //width: rpx(88);
              //height: rpx(32);
              padding: rpx(5) rpx(12);
              border-radius: rpx(16);
              border: rpx(1) solid #dddddd;
              display: flex;
              align-items: center;
              justify-content: center;
              font-size: rpx(15);
              font-weight: 400;
              color: #888888;
              &:not(:last-child) {
                margin-right: rpx(8);
              }
              &.success_wrapper {
                background: #1ab394;
                color: #ffffff;
                border: none;
              }
              &.cancelRefund {
                background: #fa9d3b;
                color: #ffffff;
                font-size: rpx(13);
                border: none;
              }

              &.error_wrapper {
                background: red;
                color: #ffffff;
                border: none;
              }
            }
            .refund_wrapper{
              color: #ffffff;
              font-size: rpx(13);
              background: #169BD5;
            }
            > .confirm_ {
              border: rpx(1) solid #fa5151;
              color: #fa5151;
            }
            > .payment_ {
              color: #ffffff;
              background: #fa5151;
            }
          }
        }
      }
    }
  }
}

/*修改tabs 的样式*/
.u-tabs-box::v-deep {
  .u-tabs {
    //background: pink !important;
    padding: rpx(0) rpx(6);
  }
}

.none_shopping {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin-top: 20vh;
  > text {
    font-size: rpx(13);
    font-weight: 400;
    color: #b2b2b2;
  }
  > image {
    width: rpx(222);
    height: rpx(158);
  }
}
</style>
